package com.martian.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Future;

/**
 * @author martian
 * @version V1.0.0
 * @Description 异步Http请求
 * @date 2023-03-29 18:12
 */

public class HttpClient {
    public static String asyncSinglePostRequest(String host, String body){
        if (null == body || body.isEmpty()){
            return null;
        }
        try {
            final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
            client.start();
            HttpEntity bodyEntity = new ByteArrayEntity(body.getBytes(StandardCharsets.UTF_8));
            HttpPost request = new HttpPost(host);
            request.setEntity(bodyEntity);
            final Future<HttpResponse> future = client.execute(request, null);
            final HttpResponse response = future.get();
            client.close();
            return getRespondContent(response);
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }
    public static String getRespondContent(HttpResponse response) throws Exception{
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8), 8);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null)
            sb.append(line).append("\n");
        return sb.toString();
    }

}
